<template>
	<view>
		<view class="pr oh" :style="{width: cut.w + 'rpx',height: cut.h + 'rpx'}">
			<image class="pa" :src="value"
			  :style="{left: img.x + 'rpx', top: img.y + 'rpx', width: img.w + 'rpx', height: img.h + 'rpx'}"
				@touchstart="touchStart"
				@touchmove="touchMove"
				@touchend="touchEnd"
			/>
		</view>
		<view class="tac py5 bgw fc-primary bt" @click="save">剪裁</view>
	</view>
</template>

<script lang="ts">

export default {
	props: {
		value: {
			type: String,
			default: ''
		}
	},
	data() {
		return {
			scale: 1,
			img: {x: 0, y: 0, w: 600, h: 600},  // 富哦之后图片区域
			cut: {w: 600, h: 600} ,// 剪裁区域,
			offset: {x: 0, y: 0} // 初始点
		}
	},
	mounted() {
		this.loadAvatar(this.value)
	},
	methods: {
		loadAvatar(val){
			const that = this
			uni.getImageInfo({
				src: val,
				success({width, height}){
					if(width >= height){
						that.img.h = that.cut.h
						that.scale = that.cut.h / height
						that.img.w = width * that.scale
						that.img.x = - (that.img.w -  that.cut.w) / 2
					} else {						
						that.img.w = that.cut.w
						that.scale = that.cut.w / width
						that.img.h = height * that.scale
						that.img.y = - (that.img.h - that.cut.h) / 2
					}		
				}
			})
		},
		touchStart({touches, changedTouches}){
			this.offset = {
				x: changedTouches[0].clientX - this.img.x,
				y: changedTouches[0].clientY - this.img.y
			}
		},
		touchMove({touches, changedTouches}){
			this.img.y = changedTouches[0].clientY - this.offset.y
			this.img.x = changedTouches[0].clientX - this.offset.x
			if(this.img.y > 0) {
				this.img.y = 0
			} else if(this.img.y + this.img.h < this.cut.h){
				this.img.y = this.cut.h - this.img.h
			}
			if(this.img.x > 0) {
				this.img.x = 0
			} else if(this.img.x + this.img.w < this.cut.w){
				this.img.x = this.cut.w - this.img.w
			}
		},
		touchEnd({touches, changedTouches}){
		},
		scrolltoupper(e){
		},
		scrolltolower(e){
			
		},
		save () {
			this.$emit('confirm', {
				x: Math.abs(this.img.x / this.scale), 
				y: Math.abs(this.img.y / this.scale), 
				w: this.cut.w / this.scale,
				h: this.cut.h / this.scale
			})
		}
	},
	watch: {
		value(newVal){
			this.loadAvatar(newVal)
		}
	}
}
</script>